# Based upon:
# https://dotnet-helpers.com/powershell/creating-a-balloon-tip-notification-using-powershell
# https://stackoverflow.com/questions/29066742/watch-file-for-changes-and-run-command-with-powershell/29067433
# Also useful:
# https://mcpmag.com/articles/2017/09/07/creating-a-balloon-tip-notification-using-powershell.aspx
# June 2020, Sean Holden

$global:FileChanged = $false

function ShowBalloonTipInfo 
{
 
[CmdletBinding()]
param
(
[Parameter()]
$Text,
 
[Parameter()]
$Title,
 
#It must be 'None','Info','Warning','Error'
$Icon = 'Info'
)
 
Add-Type -AssemblyName System.Windows.Forms
 
#So your function would have to check whether there is already an icon that you can reuse.This is done by using a "shared variable", which really is a variable that has "script:" scope.
if ($script:balloonToolTip -eq $null)
{
#we will need to add the System.Windows.Forms assembly into our PowerShell session before we can make use of the NotifyIcon class.
$script:balloonToolTip = New-Object System.Windows.Forms.NotifyIcon 
}
 
$path = Get-Process -id $pid | Select-Object -ExpandProperty Path
$balloonToolTip.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path)
$balloonToolTip.BalloonTipIcon = $Icon
$balloonToolTip.BalloonTipText = $Text
$balloonToolTip.BalloonTipTitle = $Title
$balloonToolTip.Visible = $true
 
#I thought to display the tool tip for one seconds,so i used 1000 milliseconds when I call ShowBalloonTip.
$balloonToolTip.ShowBalloonTip(1000)
}

#    $changeAction = [scriptblock]::Create('

        # This is the code which will be executed every time a file change is detected
$changeAction =         Get-Content C:\ProgramData\FileWave\FWClient\fwcld.log -tail 1 -wait | ForEach-Object {
            switch($_) {
                { $_ -match "Model version" -or $_ -match "Downloading Fileset" -or $_ -match "Done activating" -or $_ -match "Activate all" } { ShowBalloonTipInfo ("FileWave: ",$_.split("|")[4]) }
                { $_ -match "Installation" } { break }
            }
        }
#    ')

function Wait-FileChange {
    param(
        [string]$File,
        [string]$Action
    )
    $FilePath = Split-Path $File -Parent
    $FileName = Split-Path $File -Leaf
    $ScriptBlock = [scriptblock]::Create($Action)

    $Watcher = New-Object IO.FileSystemWatcher $FilePath, $FileName -Property @{ 
        IncludeSubdirectories = $false
        EnableRaisingEvents = $true
    }
    $onChange = Register-ObjectEvent $Watcher Changed -Action {$global:FileChanged = $true}

    while ($global:FileChanged -eq $false){
        Start-Sleep -Milliseconds 100
    }

    & $ScriptBlock 
    Unregister-Event -SubscriptionId $onChange.Id
}

Wait-FileChange -File C:\ProgramData\FileWave\FWClient -Action $Action
